#!/usr/bin/env node

// 测试修复后的PWM控制功能
const { changePwmPin } = require("./lib/channel");

console.log("🚀 测试修复后的PWM控制功能...");
console.log("正在测试硬件PWM (引脚13=电调, 引脚12=舵机)");

async function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function testFixedPWM() {
  console.log("\n📡 等待GPIO进程启动...");
  await sleep(2000);
  
  const tests = [
    // 电调测试
    { pin: 13, name: "电调-中性", value: 0, duration: 2000 },
    { pin: 13, name: "电调-前进慢", value: 0.2, duration: 3000 },
    { pin: 13, name: "电调-前进中", value: 0.5, duration: 3000 },
    { pin: 13, name: "电调-前进快", value: 0.8, duration: 3000 },
    { pin: 13, name: "电调-最大前进", value: 1.0, duration: 3000 },
    { pin: 13, name: "电调-回中性", value: 0, duration: 2000 },
    { pin: 13, name: "电调-后退慢", value: -0.2, duration: 3000 },
    { pin: 13, name: "电调-后退中", value: -0.5, duration: 3000 },
    { pin: 13, name: "电调-后退快", value: -0.8, duration: 3000 },
    { pin: 13, name: "电调-最大后退", value: -1.0, duration: 3000 },
    { pin: 13, name: "电调-最终中性", value: 0, duration: 2000 },
    
    // 舵机测试  
    { pin: 12, name: "舵机-中心", value: 0, duration: 2000 },
    { pin: 12, name: "舵机-右转小", value: 0.3, duration: 3000 },
    { pin: 12, name: "舵机-右转中", value: 0.6, duration: 3000 },
    { pin: 12, name: "舵机-右转大", value: 1.0, duration: 3000 },
    { pin: 12, name: "舵机-回中心", value: 0, duration: 2000 },
    { pin: 12, name: "舵机-左转小", value: -0.3, duration: 3000 },
    { pin: 12, name: "舵机-左转中", value: -0.6, duration: 3000 },
    { pin: 12, name: "舵机-左转大", value: -1.0, duration: 3000 },
    { pin: 12, name: "舵机-最终中心", value: 0, duration: 2000 }
  ];
  
  for (let i = 0; i < tests.length; i++) {
    const test = tests[i];
    console.log(`\n🎯 [${i+1}/${tests.length}] ${test.name}`);
    console.log(`   设置引脚${test.pin}为${test.value}, 持续${test.duration/1000}秒`);
    
    // 发送PWM命令
    changePwmPin(test.pin, test.value);
    
    // 等待指定时间
    await sleep(test.duration);
    
    console.log(`   ✅ 完成`);
  }
  
  console.log("\n🛑 停止所有PWM信号");
  changePwmPin(13, 0);
  changePwmPin(12, 0);
  
  await sleep(1000);
  
  console.log("\n✅ 测试完成！");
  console.log("\n🔍 检查结果:");
  console.log("1. 电调应该产生不同的蜂鸣声或电机转动");
  console.log("2. 舵机应该左右转动到不同位置");
  console.log("3. 如果仍无反应，检查硬件连接和电源供应");
  
  process.exit(0);
}

testFixedPWM().catch(error => {
  console.error("❌ 测试失败:", error);
  process.exit(1);
});